/**
 * 
 */
package pl.kaczanowscy.tomek.ipdl;

import pl.kaczanowscy.tomek.ipdl.enums.Move;

/**
 * A simple {@link Game} between two players.
 * 
 * @author Tomek Kaczanowski
 * 
 */
public final class TwoPlayersGame implements Game {

	private final int nbOfRounds;
	private final Strategy sA, sB;
	private final GameMatrix gameMatrix;

	// TODO is it ok, that you can play the same game many times ?

	public TwoPlayersGame(Strategy sA, Strategy sB, GameSettings gameSettings) {
		this.sA = sA;
		this.sB = sB;
		this.nbOfRounds = gameSettings.getNbOfRounds();
		this.gameMatrix = gameSettings.getGameMatrix();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.kaczanowscy.tomek.ipdl.Game#play()
	 */
	@Override
	public GameResult play() {
		final GameResult gameResult = new GameResultImpl(sA, sB);
		for (int i = 0; i < nbOfRounds; i++) {
			RoundResult result = playRound(gameResult);
			sA.roundEnded(result);
			sB.roundEnded(result);
		}
		return gameResult;
	}

	private RoundResult playRound(GameResult gameResult) {
		Move moveA = sA.getMove();
		Move moveB = sB.getMove();
		int payoffA = gameMatrix.getPayoff(moveA, moveB);
		int payoffB = gameMatrix.getPayoff(moveB, moveA);
		gameResult.addPayoff(sA, payoffA);
		gameResult.addPayoff(sB, payoffB);
		return new RoundResultImpl(sA, payoffA, moveA, sB, payoffB, moveB);
	}
}
